package com.travelSpring.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.travelSpring.entity.User;
import com.travelSpring.exception.UserException;
import com.travelSpring.mapper.UserMapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import javax.annotation.Resource;
import java.util.List;

/**功能：
*作者：卷心菜
*日期：2025/3/1 18:51
*/
@Service
public class UserService {
    @Resource
    UserMapper userMapper;

    public List<User> selectAll() {
      return userMapper.selectAll(null);
    }


    public PageInfo selectPage(Integer pageSize, Integer pageNum, User user) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll(user);
        return  PageInfo.of(list);
    }

    public User login(User user) {
        //验证账户是否存在
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if(dbUser == null) {
            throw new UserException("账号不存在,请先登陆");
        }
        //验证密码是否正确
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(user.getPassword(), dbUser.getPassword())) {
            throw new UserException("账号或密码错误");
        }
        return dbUser;
    }

    public void register(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if(dbUser != null) {
            throw new UserException("账户已存在");
        }
        String encodePassword=new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encodePassword);
        userMapper.insert(user);
    }
}
